package com.haier.controller.h5;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.haier.service.IHpTokenService;
import com.haier.service.IhaierService;
import com.haier.utils.EmptyUtils;
import com.haier.utils.H5Util;
import com.haier.vo.ResponseVo;

@RestController
@RequestMapping(value = "/hipassjava/h5")
public class H5LoginContoller {
	private static final Logger logger = LoggerFactory.getLogger(H5LoginContoller.class);
	@Autowired
	private IHpTokenService iHpTokenService;
	@Autowired
	private IhaierService ihaierService;

	/**
	 * 登录
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Object login(@RequestBody JSONObject params) {
		try {
			String authCode = params.getString("authCode");
			if (EmptyUtils.isEmpty(authCode)) {
				return ResponseVo.checkError("code不能为空");
			}
			// 获取accessToken,注意正是代码要有异常流处理
			String accessToken = iHpTokenService.getToken();
			// 钉钉用户
			OapiUserGetuserinfoResponse user = H5Util.getUserId(authCode, accessToken);
			if (user == null || EmptyUtils.isEmpty(user.getUserid())) {
				return ResponseVo.checkError("该code无效");
			}
			// 钉钉的用户信息 获取jobnumber
			OapiUserGetResponse userInfo = H5Util.getInfo(accessToken, user.getUserid());

			// 根据钉钉的jobnumber获取海尔的信息
			JSONObject ihaierInfo = ihaierService.getUserInfo(userInfo.getJobnumber());

			JSONObject result = new JSONObject();
			result.put("dingUserId", user.getUserid());
			result.put("jobnumber", userInfo.getJobnumber());
			result.putAll(ihaierInfo);
			return ResponseVo.success(result);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResponseVo.error();
		}
	}
}
